<template>
  <div>
    <el-form :model="form" inline>
      <el-form-item label="用户名称"
        ><el-input v-model="form.name" placeholder="请输入用户名称"></el-input
      ></el-form-item>
      <el-form-item label="用户账号"
        ><el-input-number
          v-model="form.account"
          placeholder="请输入用户账号"
        ></el-input-number
      ></el-form-item>
      <el-button type="primary" @click="search">查 询</el-button>
    </el-form>
    <el-table :data="tableData">
      <el-table-column label="账号" prop="account"></el-table-column>
      <el-table-column label="姓名" prop="name"></el-table-column>
      <el-table-column label="用户类型" prop="status">
        <template slot-scope="scope">
          <span v-for="item in type" :key="item.id">
            <span v-if="scope.row.status === item.value">
              {{ item.name }}
            </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="所在班级" prop="gradeId">
        <template slot-scope="scope">
          <span v-for="item in grades" :key="item.id">
            <span v-if="scope.row.gradeId === item.id">
              {{ item.name }}
            </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createdTime"></el-table-column>
      <el-table-column label="更新时间" prop="updatedTime"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="reset(scope.row)" size="mini" type="text"
            >重置密码</el-button
          >
          <el-button @click="detail(scope.row)" size="mini" type="text"
            >详情</el-button
          >
          <el-button @click="deleteHandler(scope.row)" size="mini" type="text"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :total="total"
      :current-page="currentPage"
      @current-change="handleCurrentChange"
    ></el-pagination>
    <el-dialog title="重置密码" :visible.sync="dialogFormVisible">
      <el-form :model="formRule" :rules="formRules" ref="formRule" inline>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="formRule.password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-button type="primary" @click="submit('formRule')">确 认</el-button>
        <el-button @click="resetForm('formRule')">重置</el-button>
      </el-form>
    </el-dialog>
    <el-dialog title="用户信息" :visible.sync="detailShow">
      <h3>用户账号：{{ userInfo.account }}</h3>
      <el-form
        :model="userInfo"
        ref="userInfo"
        :rules="userRules"
        label-width="80px"
        label-position="left"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userInfo.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <!-- 这里需要用多选框 -->
        <el-form-item label="用户类型" prop="status">
          <el-select
            v-model="userInfo.status"
            placeholder="请选择用户类型"
            @change="changeHandler"
          >
            <el-option
              v-for="item in type"
              :key="item.id"
              :label="item.name"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="userInfo.status == 2"
          label="所属班级"
          prop="gradeId"
        >
          <el-select v-model="userInfo.gradeId" placeholder="请选择所属班级">
            <el-option
              v-for="item in grades"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="userInfo.status == 2"
          label="学习类型"
          prop="license"
        >
          <el-select
            v-model="userInfo.license"
            placeholder="请选择学习类型"
            @change="changeHandler"
          >
            <el-option
              v-for="item in licenseType"
              :key="item.id"
              :label="item.type"
              :value="item.type"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="补差课程" prop="subject" v-if="showSubject">
          <el-select
            v-model="userInfo.subject"
            placeholder="请选择补差课程"
            multiple
          >
            <el-option
              v-for="item in subjects"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitHandler('userInfo')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json 文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { list, getTotal, detele, resetPassword, update } from "@/api/user";
import gradeApi from "@/api/grade/index";
import subjectApi from "@/api/subject/index";

export default {
  //import 引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value == "") {
        callback(new Error("密码必须填写！"));
      } else if (value.length < 6) {
        callback(new Error("密码位数不得小于6！"));
      } else {
        callback();
      }
    };
    //这里存放数据
    return {
      licenseType: [
        { id: 0, type: "PA" },
        { id: 1, type: "TA" },
        { id: 2, type: "补差" },
        // { id: 3, type: "DA42机型" },
      ],
      grades: [],
      detailShow: false, //显示用户信息
      userInfo: {
        account: "",
        name: "",
        status: "",
        gradeId: "",
        subject: [],
      }, //用户信息
      userRules: {
        name: [{ required: true, message: "名称不得为空！", trigger: "blur" }],
        status: [
          { required: true, message: "用户类型不得为空！", trigger: "blur" },
        ],
        license: [
          {
            required: true,
            message: "学习类型不得为空！",
            trigger: "blur",
          },
        ],
        subject: [
          {
            required: true,
            message: "补差课程不得为空！",
            trigger: "blur",
          },
        ],
      },
      type: [
        { id: 0, value: 0, name: "管理员" },
        { id: 1, value: 1, name: "教师" },
        { id: 2, value: 2, name: "学生" },
      ],
      formRule: { password: "" },
      form: { name: "", account: "" },
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogFormVisible: false,
      formRules: {
        password: {
          required: true,
          validator: validatePassword,
          trigger: "blur",
        },
      },
      id: 0,
      userForm: { status: "", id: 0 }, //user表
      showSubject: false,
      subjects: [],
    };
  },
  //计算属性 类似于 data 概念
  computed: {},
  //监控 data 中的数据变化
  watch: {},
  //方法集合
  methods: {
    changeHandler() {
      if (this.userInfo.status == 2) {
        if (this.userInfo.license == "补差") {
          //如果是补差学员，要选择其补差的课程
          this.showSubject = true;
        } else {
          this.userInfo.subject = null;
          this.showSubject = false;
        }
      } else {
        this.userInfo.subject = null;
        this.showSubject = false;
        this.userInfo.gradeId = "";
      }
    },
    submitHandler(userInfo) {
      this.$refs[userInfo].validate((valid) => {
        if (valid) {
          update(this.userInfo).then((res) => {
            this.$message({
              message: `${res.message}`,
              type: "success",
            });
            this.detailShow = false;
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    detail(params) {
      this.detailShow = true;
      if (params.subject) {
        this.userInfo = params;
        //如果设置了补差的课程信息，该信息会以json格式存储在数据库中，返回给前端就是一个string
        //这里主要是为了防止再一次打开时，会报错，所以做一个判断
        if (typeof params.subject === "string") {
          this.userInfo.subject = JSON.parse(params.subject);
        }
        this.showSubject = true;
      } else {
        this.userInfo = params;
        this.showSubject = false;
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          resetPassword(this.id, this.formRule.password).then((res) => {
            this.$message({
              message: `${res.message}`,
              type: "success",
            });
            this.dialogFormVisible = false;
            this.formRule = { password: "" };
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    deleteHandler(data) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          detele(data.id).then((res) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.list(1);
            this.getTotal();
            this.currentPage = 1;
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    reset(data) {
      this.formRule = { password: "" };
      this.id = data.id;
      this.dialogFormVisible = true;
    },
    search() {
      this.list(1);
      this.getTotal();
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.list(currentPage);
    },
    list: async function (currentPage) {
      const res = await list(
        this.form.name,
        this.form.account,
        currentPage,
        this.pageSize
      );
      this.tableData = res.data;
    },
    getTotal: async function () {
      const res = await getTotal(this.form.name, this.form.account);
      this.total = res.data;
    },
    getGrade: async function () {
      const res = await gradeApi.all();
      this.grades = res.data;
    },
  },
  //生命周期 - 创建完成（可以访问当前 this 实例）
  created() {
    this.list(1);
    this.getTotal();
    this.getGrade();
    subjectApi.getAll().then((res) => {
      this.subjects = res.data;
    });
  },
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有 keep-alive 缓存功能，这个函数会触发
};
</script>
<style scoped></style>
